<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-22 17:52:56
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\basicData\template.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="模版名称" label-width="80px">
            <el-input
              v-model="queryParams.templateName"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="模板编号">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="模板类型">
            <el-select
              v-model="queryParams.type"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="dict in dict.type.template_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <div class="tableoperation">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click.native.prevent="openDialog()"
          >添加</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="templateList"
        :height="height - 400 + 'px'"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column label="模板编号" align="center" prop="code" />
        <el-table-column label="模板名称" align="center">
          <template slot-scope="{ row }">
            <span class="imgView" @click="viewfile(row)">{{
              row.templateName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板类型" align="center">
          <template slot-scope="{ row }">
            <dict-tag :options="dict.type.template_type" :value="row.type" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="{ row }">
            <el-button
              style="margin-right: 10px"
              @click.native.prevent="openDialog(row)"
              type="text"
            >
              编辑模板
            </el-button>
            <el-button
              @click.native.prevent="handleDelete(row)"
              type="text"
              style="color: #f32d2d; margin-right: 10px"
            >
              删除
            </el-button>
            <el-button @click.native.prevent="editSignature(row)" type="text">
              编辑签章
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1200px"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :disabled="status == '3'"
        :rules="rules"
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="模板名称" prop="templateName">
              <el-select
                v-model="form.templateName"
                :placeholder="status != '3' ? '请选择' : ''"
                style="width: 100%"
                :disabled="status != '1'"
                @change="changeTemplateName"
              >
                <!-- <el-tooltip v-for="(item,index) in codeList" :key="index" class="item" effect="light" :content="item.description" placement="bottom"> -->
                <el-option
                  :label="item.description"
                  :value="item.description"
                  :key="index"
                  v-for="(item, index) in codeList"
                >
                </el-option>
                <!-- </el-tooltip> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模版类型" prop="type">
              <el-select v-model="form.type" placeholder="" disabled>
                <el-option
                  v-for="dict in dict.type.template_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模板编号" prop="code">
              <el-input v-model="form.code" disabled />
              <!-- <el-select
								v-model="form.code"
								disabled
								style="width: 100%"
								clearable>
								<el-tooltip v-for="(item,index) in codeList" :key="index" class="item" effect="light" :content="item.description" placement="bottom">
									<el-option
										:label="item.code"
										:value="item.code"
										>
									</el-option>
								</el-tooltip>
							</el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="status != '3' ? '上传附件' : '查看附件'"
              prop="ossId"
            >
              <el-input v-model="form.ossId" v-if="false" />
              <el-upload
                ref="upload"
                :action="upload.url"
                :headers="upload.headers"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleFileSuccessSecond"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
                :limit="1"
                :on-exceed="handleExceed"
                multiple
              >
                <el-button
                  v-if="status != '3'"
                  icon="el-icon-upload"
                  size="mini"
                  plain
                  type="primary"
                  >上传文件</el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" v-if="status != '3'" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="编辑签章"
      class="signature_dialog"
      :visible.sync="signatureVisible"
      :style="`width: ${width}px;`"
      fullscreen
    >
      <Signature
        :sealTypeList="sealTypeList"
        :commonSealTypeDictList="commonSealTypeDictList"
        @submit="submit"
        :fileURL="fileURL"
        :detailBoxs="detailBoxs"
        v-if="signatureVisible"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  templateList,
  templateAdd,
  templateDetail,
  templateUpdate,
  templateRemove,
  getTemplateCode,
  getSign,
  addSign,
  signToPdf,
} from "@/api/basicData/template";
import { listOss, listByIds, delOss } from "@/api/system/oss";
import { getToken } from "@/utils/auth";
import { getDicts } from "@/api/system/dict/data";

import Signature from "@/components/Signature1";

export default {
  name: "template",
  dicts: ["template_type"],
  components: { Signature },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" },
        ],
        ossId: [{ required: true, message: "附件不能为空", trigger: "change" }],
      },
      // 模板列表
      templateList: [],
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      // 视图高度
      height: document.documentElement.clientHeight,
      // 视图宽度
      width: 1000,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Disposition": "inline",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      },
      fileList: [],
      // 编码下拉框
      codeList: [],
      signatureVisible: false,
      sealTypeList: [],
      openRow: null,
      fileURL: null,
      detailBoxs: [],
      commonSealTypeDictList: [],
    };
  },
  created() {
    this.getList();
    this.getCodeList();
    getDicts("seal_type").then((response) => {
      this.sealTypeList = response.data || [];
    });
    getDicts("common_seal_type").then((response) => {
      this.commonSealTypeDictList = response.data || [];
    });
  },
  methods: {
    // 获取模板列表
    getList() {
      this.loading = true;
      templateList(this.queryParams)
        .then((response) => {
          this.templateList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取编码下拉
    getCodeList() {
      getTemplateCode().then((response) => {
        this.codeList = response.data;
      });
    },
    // 打开对话框
    openDialog(row, status) {
      this.resetFormmy();
      if (row) {
        templateDetail(row.templateId).then((response) => {
          this.form = response.data;
          if (this.form.type) {
            this.$set(this.form, "type", this.form.type.toString());
          } else {
            let findobj = this.codeList.find(
              (item) => item.description == this.form.templateName
            );
            if (findobj) {
              this.$set(this.form, "type", findobj.type.toString());
            }
          }
          if (this.form.ossId) {
            listByIds(this.form.ossId).then((response) => {
              this.fileList = response.data;
              this.fileList.forEach((item) => {
                item.name = item.originalName;
              });
            });
          }
          this.dialogVisible = true;
        });
        if (status == "3") {
          this.status = "3";
          this.title = "查看模板";
        } else {
          this.status = "2";
          this.title = "编辑模板";
        }
        this.dialogVisible = true;
      } else {
        this.status = "1";
        this.title = "添加模板";
        this.dialogVisible = true;
      }
    },
    // 重置表单
    resetFormmy() {
      this.form = {};
      this.resetForm("form");
      this.fileList = [];
    },
    // 提交按钮
    submitForm() {
      let ossId = this.fileList
        .map((item) => {
          if (item.ossId) {
            return item.ossId; /* 回显的列表格式 */
          } else if (item.response.data) {
            return item.response.data.ossId; /* 新上传的列表格式 */
          }
        })
        .join(",");
      this.$set(this.form, "ossId", ossId);
      console.log("this.form.ossId", this.form.ossId);
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        if (this.status == "1") {
          templateAdd(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else if (this.status == "2") {
          templateUpdate(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除模板[${row.templateName}]？`)
        .then(() => {
          this.loading = true;
          return templateRemove(row.templateId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 更改模版名称
    changeTemplateName(val) {
      let findobj = this.codeList.find((item) => item.description == val);
      if (findobj) {
        this.$set(this.form, "type", findobj.type.toString());
        this.$set(this.form, "code", findobj.code);
      }
    },
    // 编辑签章
    async editSignature(row) {
      this.openRow = row;
      this.fileURL = "";
      await getSign({
        templateId: row.templateId,
      }).then((response) => {
        if (response.data) {
          this.detailBoxs = response.data;
        }
      });

      await signToPdf(row.ossId).then((response) => {
        console.log("response", response);
        let blob = new Blob([response], {
          type: "application/pdf;chartset=UTF-8",
        });
        let fileURL = URL.createObjectURL(blob);
        this.fileURL = fileURL;
        console.log("fileURL11111", fileURL);
      });

      this.signatureVisible = true;
      this.width = document.documentElement.clientWidth;
      // this.width = 2200;
    },
    // 提交签章
    submit(arr) {
      console.log("提交签章", arr);
      arr.forEach((item) => {
        item.templateId = this.openRow.templateId;
      });
      addSign(arr).then((response) => {
        this.$modal.msgSuccess("保存成功");
        this.signatureVisible = false;
      });
    },
    // 文件移除
    handleRemove(file, fileList) {
      console.log("handleRemove", fileList);
      this.fileList = fileList;
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      console.log("response, file, fileList", response, file, fileList);
      if (response.code == 500) {
        this.$modal.msgWarning(response.msg);
      }
      this.fileList = fileList;
      console.log("this.form", this.form);
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 列表文件预览
    viewfile(row) {
      if (row.ossId) {
        signToPdf(row.ossId).then((response) => {
          console.log("response", response);
          let blob = new Blob([response], {
            type: "application/pdf;chartset=UTF-8",
          });
          let fileURL = URL.createObjectURL(blob);
          console.log("fileURL", fileURL);
          window.open(fileURL);
        });
      }
    },
    // 弹框文件预览
    handlePreview(file, fileList) {
      console.log("handlePreview", file, fileList);
      // 上传时
      if (file.response && file.response.data) {
        window.open(file.response.data.url);
      } else if (file.url) {
        window.open(file.url);
      }
    },
    // 上传前
    beforeAvatarUpload(file) {
      console.log("file", file);
      let lastIndex = file.name.lastIndexOf(".");
      let suffix = file.name.substring(lastIndex + 1);
      console.log("suffix", suffix);
      if (suffix != "docx") {
        this.$message.warning("仅支持docx格式，请重新上传!");
        return false;
      } else {
        return true;
      }
    },
    // 超出数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
  },
};
</script>

<style lang="scss" scoped>
.operation {
  margin-block: 30px;
}
.imgView {
  color: #2a72ee;
  cursor: pointer;
  margin-right: 10px;
  &:hover {
    text-decoration: underline;
  }
}
::v-deep .el-upload-list.is-disabled {
  margin-top: -35px;
  .el-upload-list__item-status-label {
    display: none;
  }
}
.signature_dialog {
  ::v-deep .el-dialog {
    max-height: 100%;
    height: 100%;
    .el-dialog__body {
      padding: 0;
    }
  }
}
</style>
